/**
 * 
 */
package com.vector.ding.web.controller;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.vector.ding.commons.ActionResult;
import com.vector.ding.commons.Constant;

/**
 * @author vector
 *
 */
@Controller
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	/**
	 * 登录操作
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = Constant.LOGIN_URL, method = RequestMethod.POST)
	public JSONObject login(String username, String password) {
		Subject curUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			curUser.login(token);
		} catch (UnknownAccountException e) {
			logger.info(e.getMessage());
			return ActionResult.fail("用户名或密码不正确！");
		} catch (AuthenticationException e) {
			logger.info("user [username={}, password={}] login error:{}",
					username, password, e.getMessage());
			return ActionResult.fail(String.format(
					"登陆异常:%s", e.getMessage()));
		}
		
		return ActionResult.success();
	}
	
	@RequestMapping(value = "logout.do", method = RequestMethod.GET)
	public ModelAndView logout() {
		Subject curUser = SecurityUtils.getSubject();
		if (curUser.isAuthenticated()) {
			curUser.logout();
		}
		
		return new ModelAndView("login");
	}
	
}
